const express = require('express');
const cors = require('cors');
const faceApiRouter = require('./face-api');
const path = require('path');
const fs = require('fs');

const app = express();
const port = 3000;

console.log('正在启动服务器...');

// 启用CORS
app.use(cors());
console.log('CORS 已启用');

// 解析JSON请求体
app.use(express.json());
console.log('JSON 解析器已启用');

// 数据库文件路径
const dbPath = path.join(__dirname, 'db.json');
console.log('数据库文件路径:', dbPath);

// 确保数据库文件存在
if (!fs.existsSync(dbPath)) {
  console.log('创建新的数据库文件');
  fs.writeFileSync(dbPath, JSON.stringify({ users: [] }));
}

// 查询用户
app.get('/user', (req, res) => {
  try {
    console.log('收到用户查询请求:', req.query);
    const db = JSON.parse(fs.readFileSync(dbPath, 'utf8'));
    console.log('当前数据库内容:', db);
    let users = db.users || [];
    console.log('用户列表:', users);
    const { zh, mm, phone, yx } = req.query;
    if (zh) {
      console.log('按账号查询:', zh);
      users = users.filter(user => user.zh === zh);
      console.log('查询结果:', users);
    }
    if (mm) users = users.filter(user => user.mm === mm);
    if (phone) users = users.filter(user => user.phone === phone);
    if (yx) users = users.filter(user => user.yx === yx);
    res.json(users);
  } catch (error) {
    console.error('查询用户时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

// 注册用户
app.post('/user', (req, res) => {
  try {
    console.log('收到用户注册请求:', req.body);
    const db = JSON.parse(fs.readFileSync(dbPath, 'utf8'));
    console.log('当前数据库内容:', db);
    const { zh, mm, phone } = req.body;
    if (!zh || !mm) {
      console.log('账号或密码为空');
      return res.status(400).json({ error: '账号和密码不能为空' });
    }
    if (db.users.some(user => user.zh === zh)) {
      console.log('账号已存在:', zh);
      return res.status(400).json({ error: '账号已存在' });
    }
    const newUser = { 
      id: Date.now().toString(), 
      zh, 
      mm, 
      phone: phone || '', 
      createdAt: new Date().toISOString() 
    };
    console.log('创建新用户:', newUser);
    db.users.push(newUser);
    fs.writeFileSync(dbPath, JSON.stringify(db, null, 2));
    console.log('用户数据已保存');
    res.status(201).json(newUser);
  } catch (error) {
    console.error('注册用户时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

// 使用人脸识别API
app.use('/api/face', faceApiRouter);
console.log('人脸识别 API 路由已启用');

// 添加测试路由
app.get('/test', (req, res) => {
  res.json({ 
    message: '服务器运行正常',
    dbPath: dbPath,
    routes: {
      user: '/user',
      faceRegister: '/api/face/register',
      faceVerify: '/api/face/verify'
    }
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
  console.log('测试路由: http://localhost:3000/test');
  console.log('用户API: http://localhost:3000/user');
  console.log('人脸注册API: http://localhost:3000/api/face/register');
}); 